package zpe.controledeacesso.jsf.view.bean;


import static zpe.genericcrud.jsf.view.bean.FacesUtils.addErrorMessage;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;

import zpe.controledeacesso.model.bean.Modulo;
import zpe.controledeacesso.service.ModuloService;
import zpe.genericcrud.exception.ApplicationException;
import zpe.genericcrud.jsf.view.bean.AbstractCrudBean;

@ManagedBean(name="moduloBean")
@ViewScoped
public class ModuloBean extends AbstractCrudBean<Modulo, ModuloService> {

	private List<SelectItem> itens = new ArrayList<SelectItem>();

	@ManagedProperty("#{moduloService}")
	protected ModuloService service;

	@Override
	public void setService(ModuloService service) {
		super.setService(service);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<SelectItem> getAllSelectItem() {	
		if( itens.isEmpty() ){
			return  beanToSelectItem( (List<Modulo> )getService().findAll((Class)getEntity().getClass(), "descricao" ) ) ;
		}else{
			return itens;
		}		
	}

	@Override
	public void save(ActionEvent event) {
		try{
			if (getService().findModuloExistente(getEntity().getDescricao())) {
				throw new ApplicationException("Módulo já cadastrado.");
			}

			super.save(event);
		} catch ( ApplicationException e ) {
			addErrorMessage( e.getMessage() );
		} catch ( Exception e ) {
			addErrorMessage( getMessage( "ERROR_INSERT" ) );
		}
	}

	@Override
	public void update(ActionEvent event) {
		try {
			if (getService().findModuloExistente(getEntity())) {
				throw new ApplicationException("Módulo já cadastrado.");
			}

			super.update(event);
		} catch ( ApplicationException e ) {
			addErrorMessage( e.getMessage() );
		} catch ( Exception e ) {
			addErrorMessage( getMessage( "ERROR_INSERT" ) );
		}
	}

	/**
	 * Preenche a lista de módulos.
	 * @param entities
	 * @return
	 */
	protected List<SelectItem> beanToSelectItem (List<Modulo> entities){

		for (Modulo e : entities ){		

			SelectItem si = new SelectItem();
			si.setLabel(e.getDescricao());
			si.setValue(e);
			itens.add(si);			
		}

		return itens;
	}

	@Override
	public void find(ActionEvent event) {
		super.find(event);
	}
}
